package com.wuhao.code.check.highlight

import com.aegis.mybatis.xmlless.constant.SQLKeywords
import com.intellij.codeInsight.daemon.impl.HighlightInfoType
import com.intellij.lang.annotation.AnnotationHolder
import com.intellij.lang.annotation.Annotator
import com.intellij.openapi.editor.DefaultLanguageHighlighterColors
import com.intellij.openapi.editor.colors.TextAttributesKey
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import com.intellij.psi.xml.XmlTag
import com.intellij.psi.xml.XmlText
import com.intellij.psi.xml.XmlToken
import com.wuhao.code.check.gotohandler.getRealColumnName
import org.jetbrains.kotlin.idea.editor.fixers.range
import org.jetbrains.kotlin.psi.psiUtil.parents
import org.jetbrains.kotlin.psi.psiUtil.startOffset


/**
 * Created by 吴昊 on 2023/12/11.
 *
 * @author 吴昊
 * @version 1.0
 * @date 2023/12/11 12:51
 * @since v0.0.0
 */
class ConvertToEntityXmlScriptHighlighter : Annotator {

  private val extraKeywords = listOf("LIKE", "ILIKE")
  private val operators = listOf(">", "<", "=", "<=", ">=")

  override fun annotate(element: PsiElement, holder: AnnotationHolder) {
    if (element !is XmlToken) {
      return
    }
    if (element.parent !is XmlText) {
      return
    }
    if (element.parents.any { it is XmlTag && it.name in listOf("if", "trim", "when", "otherwise") }) {
      if (element.text.uppercase() in SQLKeywords.getValues() + extraKeywords) {
        highlight(
            0, element.text.length, holder, element, DefaultLanguageHighlighterColors.KEYWORD
        )
      } else if (element.text in operators) {
        highlight(
            0, element.text.length, holder, element, DefaultLanguageHighlighterColors.OPERATION_SIGN
        )
      } else if (element.text.contains(".")) {
        if (element.text.contains("#{")) {
          return
        }
        val realColumn = getRealColumnName(element)
        val start = realColumn.second - element.startOffset + realColumn.first.indexOf(".") + 1
        val end = realColumn.third - element.startOffset
        highlight(
            start, end,
            holder, element, DefaultLanguageHighlighterColors.INSTANCE_FIELD
        )
      }
    }
  }

  private fun highlight(
      start: Int,
      end: Int,
      holder: AnnotationHolder,
      entry: PsiElement,
      key: TextAttributesKey
  ) {
    val builder = holder.newAnnotation(
        HighlightInfoType.HIGHLIGHTED_REFERENCE_SEVERITY, ""
    )
    builder.textAttributes(key)
    builder.range(TextRange(entry.range.startOffset + start, entry.range.startOffset + end))
    builder.create()
  }

}
